package collect

type Queue[T any] struct {
	head *node[T]
	end  *node[T]
	len  int
}

// Push 是向队列中放入一个元素
func (q *Queue[T]) Push(data T) {
	newNode := &node[T]{
		data: data,
	}
	defer func() {
		q.len++
	}()

	if q.head == nil {
		q.head = newNode
		q.end = newNode
		return
	}

	q.end.next = newNode
	q.end = newNode
}

// Top 是返回队头元素
func (q *Queue[T]) Top() T {
	if q.head == nil {
		panic("队列为空")
	}

	return q.head.data
}

// Pop 是弹出队头元素
func (q *Queue[T]) Pop() {
	if q.head == nil {
		panic("队列为空")
	}
	defer func() {
		q.len--
	}()

	if q.len == 1 {
		q.head = nil
		q.end = nil
		return
	}

	q.head = q.head.next
}

// Len 是返回队列长度
func (q *Queue[T]) Len() int {
	return q.len
}
